package com.corange.insuranceinformation.common.utils;

import com.corange.insuranceinformation.modules.metadata.vo.MetaDataVO;
import com.corange.insuranceinformation.modules.metadata.vo.MetaPageVO;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * author: willinggod
 * content: cache the data
 */
public class CacheUtils {
    public static Map<String,MetaDataVO> cacheMap=new HashMap<>();
    /**
     *  data source path
     */
     static final String dataSourceJsonPath="data.json";

    /**
     *  获取初始化数据
     * @author willinggod
     */
    public static List<MetaDataVO> getInitData() throws IOException {
        Gson gson=new Gson();
        String jsonStr = CacheUtils.readJsonFile(dataSourceJsonPath);
        if(StringUtils.isNotBlank(jsonStr)){
            return gson.fromJson(jsonStr,new TypeToken<List<MetaDataVO>>(){}.getType());
        }else{
            return null;
        }
    }

    /**
     *  初始化内存数据
     * @author willinggod
     */
    public static   void initCache() throws IOException {
        List<MetaDataVO> metaDataVOS=CacheUtils.getInitData();
        for(MetaDataVO metaDataVO:metaDataVOS){
            StringBuffer stringBuffer=new StringBuffer();
            String keyName=stringBuffer.append(metaDataVO.getMetadataNameCN()).append("_").
                    append(metaDataVO.getClass()).append("_").append(metaDataVO.getMetadataCode()).toString();
            cacheMap.put(keyName,metaDataVO);
        }
    }
    /**
     * 读取json文件，返回json串
     * @param fileName
     * @author willinggod
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            ClassPathResource classPathResource = new ClassPathResource(fileName);
            InputStream inputStream =classPathResource.getInputStream();
            Reader reader = new InputStreamReader(inputStream,"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 根据关键字模糊查询属性
     * @param keyName 模糊查询关键字
     * @author willinggod
     */
    public static List<MetaDataVO> searchMetaDataByKeyName(String keyName){
        if(cacheMap.isEmpty()){
            return null;
        }else{
            List<MetaDataVO> metaDataVOList=new ArrayList<>();
            for (Map.Entry<String, MetaDataVO> entity : cacheMap.entrySet()) {
                if(null!=entity.getKey() && entity.getKey().indexOf(keyName)>-1){
                    metaDataVOList.add(entity.getValue());
                }
            }
            return metaDataVOList;
        }
    }
    /**
     * 根据关键字模糊查询属性-待分页功能
     * @param keyName 模糊查询关键字
     * @param pageSize
     * @param currentPage
     * @author willinggod
     */
    public static MetaPageVO searchMetaDataByKeyNameForPages(String keyName, Integer pageSize, Integer currentPage){
        List<MetaDataVO>  metaDataVOList=searchMetaDataByKeyName(keyName);
        MetaPageVO metaPageVO=new MetaPageVO();
        metaPageVO.setCurrentPage(currentPage);
        metaPageVO.setPageSize(pageSize);
        if(CollectionUtils.isEmpty(metaDataVOList)){
            List<MetaDataVO> metaDataList=new ArrayList<>();
            Integer totalSize=metaDataVOList.size();
            metaPageVO.setTotalSize(totalSize);
            //首先计算按照每页的页数，能够展示多少页
            int pageNum=totalSize.intValue()/pageSize.intValue();
            pageNum=pageSize*pageNum==totalSize?pageNum:pageNum+1;
            if(currentPage<=pageNum){
               int indexStart=currentPage*pageSize;
               int indexEnd=currentPage*pageSize+pageSize;
               if(indexStart>totalSize){
                   indexStart=totalSize;
               }
               if(indexEnd > totalSize ){
                   indexEnd=totalSize;
               }
               for(int i=indexStart;i<indexEnd;i++){
                   metaDataList.add(metaDataVOList.get(i));
               }
            }
            metaPageVO.setMetaDataList(metaDataList);
        }else{
            metaPageVO.setTotalSize(0);
        }
        return metaPageVO;
    }
}
